import React from 'react'
import {Card,Form,Input,Button,message} from 'antd'
import {UserOutlined,LockOutlined} from '@ant-design/icons'
import './index.scss'
import {useDispatch} from 'react-redux'
import {loginAsync} from '../../store/modules/adminReducer'
import withRouter from '../../hoc/withRouter'
export default withRouter((props)=>{
    const dispatch=useDispatch()
    const login=async(arg)=>{
        //由于dispcth()的返回值是一个Promise，是一个异步的，所以为了保证后续的内容在这个disptch之后完成，需要是使用await来控制
        try {
            await dispatch(loginAsync(arg))
            //跳转
            props.navigate('/')
            //提示
            message.success('登录成功')
        } catch (error) {
            message.warning('用户名或者密码有误')
        }
    }  

    // 验证用户名规则的方法
    const validatorUserName=(_,value)=>{
        const reg=/^[a-zA-Z0-9]{6,12}$/
        if(!reg.test(value)){
            return Promise.reject(new Error('用户名格式有误'))
        }
        return Promise.resolve()
    }
    //验证密码规则的方法
    const validatorPwd=(_,value)=>{
        const reg=/^[a-zA-Z0-9]{6,12}$/
        if(!reg.test(value)){
            return Promise.reject(new Error('密码格式有误'))
        }
        return Promise.resolve()
    }
    return (<div className='login-container'>
        <Card className='login-box'>
            <div className='login-title'>赤兔养车用户登录</div>
            <Form onFinish={login}>
                <Form.Item name="username" 
                hasFeedback
                validateTrigger="onBlur"
                rules={[
                    {
                        required:true,
                        message:'用户名不能为空'
                    },
                    {
                        validator:validatorUserName
                    }
                ]}>
                    <Input prefix={<UserOutlined />}></Input>
                </Form.Item>
                <Form.Item name="password"
                hasFeedback
                validateTrigger="onBlur"
                rules={[
                    {
                        required:true,
                        message:'密码不能为空'
                    },
                    {
                        validator:validatorPwd
                    }
                ]}>
                    <Input.Password prefix={<LockOutlined />}></Input.Password>
                </Form.Item>
                <Form.Item>
                    <Button className='login-btn' type='primary' htmlType='submit'>登录</Button>
                </Form.Item>
            </Form>
        </Card>
    </div>)
})